<template>
  <div class="personal-center">
    <a-card title="个人中心" :bordered="false" class="profile-card">
      <div class="user-info">
        <div class="avatar-section">
          <a-upload
            action="/"
            :show-file-list="false"
            :custom-request="updateAvatar"
          >
            <template #upload-button>
              <div class="avatar-wrapper">
                <a-avatar :size="120" class="avatar" show-loader>
                  <img
                    :src="userInfo.avatar ?? require('@/assets/logo.png')"
                    alt="头像"
                  />
                </a-avatar>
                <!-- <div class="avatar-mask">
                  <icon-edit :size="24" />
                </div> -->
              </div>
            </template>
          </a-upload>
        </div>

        <div class="base-info">
          <h2>{{ userInfo.username }}</h2>
          <div class="account-info">
            <a-tag color="blue" style="width: 50px">{{ userInfo.role }}</a-tag>
            <span><icon-user /> 账号：{{ userInfo.account }}</span>
            <span><icon-email /> 个人简介：{{ userInfo.userProfile }}</span>
          </div>
        </div>
      </div>
    </a-card>

    <a-row :gutter="20" class="content-row">
      <a-col :span="12">
        <a-card :title="computedTitle()" class="comment-card">
          <a-list :data="comments">
            <template #item="{ item }">
              <a-list-item>
                <!-- 新增一个容器，用于相对定位 -->
                <div class="comment-wrapper">
                  <div class="comment-item">
                    <!-- 显示标题 -->
                    <div class="comment-title">{{ item.title }}</div>
                    <div class="comment-content">{{ item.content }}</div>
                    <div class="comment-time">
                      {{ moment(item.time).format("YYYY-MM-DD HH:mm:ss") }}
                    </div>
                    <a-button
                      type="text"
                      class="delete-btn"
                      @click.stop="handleDelete(item, index)"
                    >
                      <icon-delete :size="18" />
                    </a-button>
                  </div>
                </div>
              </a-list-item>
            </template>
          </a-list>
          <div class="load-more-wrapper">
            <a-button
              v-if="showLoadMore"
              class="load-more-btn"
              @click="handleLoadMore"
              :loading="loading"
            >
              加载更多
            </a-button>
          </div>
        </a-card>
      </a-col>

      <a-col :span="12">
        <a-card title="编辑信息" class="edit-card">
          <a-form :model="editForm" layout="vertical">
            <a-form-item label="用户名" field="username">
              <a-input v-model="editForm.userName" placeholder="请输入用户名" />
            </a-form-item>
            <a-form-item label="个人简介" field="userProfile">
              <a-input
                v-model="editForm.userProfile"
                placeholder="请输入个人简介"
              />
            </a-form-item>
            <a-button type="primary" @click="handleSaveInfo">保存修改</a-button>
          </a-form>

          <a-divider />

          <a-form :model="passwordForm" layout="vertical" class="password-form">
            <a-form-item label="旧密码" field="oldPassword">
              <a-input-password v-model="passwordForm.oldPassword" />
            </a-form-item>
            <a-form-item label="新密码" field="newPassword">
              <a-input-password v-model="passwordForm.newPassword" />
            </a-form-item>
            <a-form-item label="确认密码" field="confirmPassword">
              <a-input-password v-model="passwordForm.confirmPassword" />
            </a-form-item>
            <a-button type="primary" @click="handleResetPassword"
              >重置密码</a-button
            >
          </a-form>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from "vue";
import { Message } from "@arco-design/web-vue";
import { UserControllerService } from "../../generated";
import { CommentControllerService } from "../../generated/services/CommentControllerService";
import { useStore } from "vuex";
import { IconEye, IconEdit, IconDelete } from "@arco-design/web-vue/es/icon";
import moment from "moment";
const store = useStore();
const loadData = async () => {
  const res = await UserControllerService.getCurrentUserUsingGet();

  console.log(res);
  userInfo.username = res.userName;
  userInfo.avatar = res.userAvatar;
  userInfo.account = res.userAccount;
  userInfo.userProfile = res.userProfile;
  userInfo.role = res.userRole;
  editForm.userName = res.userName;
  editForm.userProfile = res.userProfile;
  editForm.userAvatar = res.userAvatar;
};
const loadComments = async () => {
  const res = await CommentControllerService.showMyCommentsUsingPost("", {
    pageSize: page.value,
  });
  console.log(res);
  comments.splice(0, comments.length, ...res.data.myCommentVOList);
  total.value = res.data.totalCount;
};
const total = ref(0);
const computedTitle = () => {
  if (total.value > 0 || total.value <= 99) {
    return "我的评论(" + total.value + ")";
  } else if (total.value > 99) {
    return "我的评论(99+)";
  } else {
    return "暂无评论";
  }
};
onMounted(async () => {
  await loadData();
  await loadComments();
});
const userInfo = reactive({
  avatar: "",
  username: "",
  account: "",
  userProfile: "",
  role: "user",
});

const editForm = reactive({
  userName: "",
  userProfile: "",
  userAvatar: "",
});
const showLoadMore = computed(() => page.value < total.value);

const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});
const page = ref(5);
const comments = reactive([
  { id: 1, content: "这个产品非常好用！", time: "2024-03-15", title: "题目1" },

  {
    id: 2,
    content: "服务响应速度很快，点个赞",
    time: "2024-03-14",
    title: "题目2",
  },
  { id: 3, content: "希望能增加更多功能", time: "2024-03-13", title: "题目3" },
]);
// 假设使用 axios
import axios from "axios";

const uploadFileUsingPost = async (formData) => {
  console.log(store.state.user.token);
  return axios.post("http://localhost:8101/api/user/user/upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data", // 确保设置正确的 Content-Type
      Authorization: store.state.user.token, // 添加 Authorization 头
    },
    withCredentials: true,
  });
};
//修改头像
const updateAvatar = async (option) => {
  const { onError, onSuccess, fileItem } = option;
  const formData = new FormData();

  // 添加业务参数
  formData.append("biz", "user_avatar");
  // 添加文件，字段名需与后端接口一致（如 "file"）
  formData.append("file", fileItem.file, fileItem.file.name); // 第三个参数是文件名（可选）

  // 调用上传接口，仅传递 formData
  const res = await uploadFileUsingPost(formData);
  console.log(res.data.data);
  userInfo.avatar = res.data.data;
  editForm.userAvatar = res.data.data;
};

const handleDelete = async (item, index) => {
  // 若需要与后端交互，可在此调用删除评论接口
  console.log(item);
  const res = await CommentControllerService.deleteCommentUsingPost({
    id: item.id.toString(),
  });
  if (res.data === true) {
    Message.success("评论删除成功");
    await loadComments();
  } else {
    Message.error("评论删除失败");
  }
};
const handleLoadMore = async () => {
  page.value += 5;
  await loadComments();
};
const handleSaveInfo = async () => {
  console.log(editForm);
  const res = await UserControllerService.editUserUsingPost("", {
    userName: editForm.userName,
    userProfile: editForm.userProfile,
    userAvatar: editForm.userAvatar,
  });
  if (res.code === 0) {
    loadData();
    //更新vuex
    store.state.user.loginUser.userAvatar = editForm.userAvatar;
    store.state.user.loginUser.userName = editForm.userName;
    store.state.user.loginUser.userProfile = editForm.userProfile;
    Message.success("信息更新成功");
  } else {
    Message.error("信息更新失败");
  }
};

const handleResetPassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    Message.error("两次输入的密码不一致");
    return;
  }
  const res = await UserControllerService.resetPasswordUsingPost({
    oldPassword: passwordForm.oldPassword,
    newPassword: passwordForm.newPassword,
  });
  if (res.code === 0) {
    Message.success("密码重置成功");
  } else {
    Message.error("密码重置失败" + res.message);
  }
};
</script>

<style scoped>
.personal-center {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.profile-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  padding: 20px;
}

.avatar-section {
  position: relative;
  margin-right: 40px;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
  transition: transform 0.3s;
}

.avatar-wrapper:hover {
  transform: scale(1.05);
}
/* 新增容器，每个评论项的删除按钮基于此容器做绝对定位 */
.comment-wrapper {
  position: relative;
  padding-right: 40px; /* 给右侧留出空间，防止内容被删除按钮遮挡 */
  width: 100%;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

/* 删除按钮样式 */
.delete-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  color: #ff4d4f;
  z-index: 1;
}
.avatar-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .avatar-mask {
  opacity: 1;
}

.base-info h2 {
  margin: 0 0 10px;
  font-size: 24px;
  color: #1a1a1a;
}
.comment-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.account-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: #666;
}

.account-info span {
  display: flex;
  align-items: center;
  gap: 6px;
}

.content-row {
  margin-top: 20px;
}

.comment-card,
.edit-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.comment-item {
  width: 100%;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.comment-content {
  color: #333;
  margin-bottom: 6px;
}

.comment-time {
  color: #999;
  font-size: 12px;
}

.password-form {
  margin-top: 20px;
}

:deep(.arco-form-item-label) {
  font-weight: 500;
}

.arco-btn {
  margin-top: 10px;
}
/* 新增的加载更多按钮样式 */
.load-more-wrapper {
  text-align: center;
  margin: 20px 0;
}

.load-more-btn {
  background-color: var(--color-primary);
  color: white;
  border-radius: 20px;
  padding: 8px 32px;
  transition: all 0.3s ease;
}

.load-more-btn:hover {
  background-color: var(--color-primary-light-2);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.load-more-btn:active {
  transform: translateY(0);
}
</style>
